package xyz.hubery.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.StringUtils;
import xyz.hubery.dto.UserDTO;
import xyz.hubery.feign.UserFeign;
import xyz.hubery.mapper.WorkIssueMapper;
import xyz.hubery.domain.WorkIssue;
import xyz.hubery.service.WorkIssueService;

@Service
public class WorkIssueServiceImpl extends ServiceImpl<WorkIssueMapper, WorkIssue> implements WorkIssueService {

    @Autowired
    private UserFeign userFeign;

    @Override
    public Page<WorkIssue> issueList(Long userId, Page<WorkIssue> page) {
        return page(page,new LambdaQueryWrapper<WorkIssue>()
                .eq(WorkIssue::getUserId,userId)
                .orderByDesc(WorkIssue::getCreated));
    }

    @Override
    public Page<WorkIssue> findByPage(Page<WorkIssue> page, Integer status, String startTime, String endTime) {
        page.addOrder(OrderItem.desc("last_update_time"));
        Page<WorkIssue> workIssuePage = page(page, new LambdaQueryWrapper<WorkIssue>().eq(status != null, WorkIssue::getStatus, status)
                .between(!StringUtils.isEmpty(startTime) && !StringUtils.isEmpty(endTime), WorkIssue::getCreated, startTime, endTime)
        );

        // 填充会员用户基础信息
        List<WorkIssue> records = workIssuePage.getRecords();
        if (records == null) {
            return workIssuePage;
        }
        // 收集用户ID列表
        List<Long> ids = records.stream().map(WorkIssue::getUserId).distinct().collect(Collectors.toList());
        // 发起远程调用
        List<UserDTO> basicUserInfo = userFeign.getBasicUserInfo(ids);
        Map<Long, UserDTO> idMappings = basicUserInfo.stream().collect(Collectors.toMap(UserDTO::getId, userDto -> userDto));
        // 填充用户信息
        records.forEach(workIssue -> {
            UserDTO userDTO = idMappings.get(workIssue.getUserId());
            workIssue.setUsername(userDTO == null ?"测试用户": userDTO.getUsername());
            workIssue.setRealName(userDTO == null ?"测试用户": userDTO.getRealName());
        });
        return workIssuePage;
    }
}
